﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UtilZ.Dotnet.Ex.Communication.Net.Telnet.Commands
{
    internal class TelnetCommandManager
    {
        private static readonly Dictionary<string, ITelnetCommand> _commandDic;


        static TelnetCommandManager()
        {
            _commandDic = new Dictionary<string, ITelnetCommand>();

            Type selfType = typeof(TelnetCommandManager);
            Type[] typeArr = selfType.Assembly.GetTypes().Where(t =>
            {
                return string.Equals(t.Namespace, selfType.Namespace);
            }).ToArray();
            Type itelnetCommandType = typeof(ITelnetCommand);
            Type telnetCommandAttributeType = typeof(TelnetCommandAttribute);
            object[] attris;
            TelnetCommandAttribute attribute;
            ITelnetCommand command;

            foreach (var type in typeArr)
            {
                if (!type.IsClass ||
                    type.IsAbstract ||
                    type.GetInterface(itelnetCommandType.Name) == null)
                {
                    continue;
                }

                attris = type.GetCustomAttributes(telnetCommandAttributeType, false);
                if (attris.Length == 0)
                {
                    continue;
                }

                attribute = (TelnetCommandAttribute)attris.First();
                if (_commandDic.ContainsKey(attribute.Command))
                {
                    throw new ArgumentException($"Telnet命令\"{attribute.Command}\"重复");
                }

                command = (ITelnetCommand)Activator.CreateInstance(type);
                _commandDic.Add(attribute.Command, command);
            }
        }

        public static bool TryGetTelnetCommand(string command, out ITelnetCommand telnetCommand)
        {
            return _commandDic.TryGetValue(command, out telnetCommand);
        }
    }
}
